import store from '@/store'

function checkPermission(el, binding) {
  const { value } = binding

  const permissions = store.getters && store.getters.permissions
  // const permissions = store.state && store.state.user && store.state.user.permissions
  if (value && value instanceof Array) {
    if (value.length > 0) {
      // return true
      const permissionBtns = value

      let checker = (arr, target) => target.every(v => arr.includes(v))
      const hasPermission = checker(permissions, permissionBtns)
      // const hasPermission = permissions.some(permission => {
      //   return permissionBtns.includes(permission)
      // })

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      return true
    }
  } else {
    throw new Error(`need roles! Like v-permission="['admin','editor']"`)
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
